package com.tangcl.module_base.network

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.tangcl.module_base.log.LogUtils
import com.tangcl.module_base.utils.ConstantUtils
import com.tangcl.module_base.network.config.LocalCookieJar
import com.tangcl.module_base.network.factory.NullToEmptyAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Created by TCL on 2021/7/7
 *
 * description:
 */
object RetrofitManager {
    private var mRetrofit: Retrofit? = null

    private val gson:Gson = GsonBuilder().registerTypeAdapterFactory(NullToEmptyAdapterFactory()).create()
    private val mOkClient = OkHttpClient
        .Builder()
        .callTimeout(ConstantUtils.NET_WORK_TIMEOUT, TimeUnit.SECONDS)
        .connectTimeout(ConstantUtils.NET_WORK_TIMEOUT, TimeUnit.SECONDS)
        .readTimeout(ConstantUtils.NET_WORK_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(ConstantUtils.NET_WORK_TIMEOUT, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)
        .cookieJar(LocalCookieJar())
//        .addInterceptor(AddQueryParameterInterceptor())//添加参数拦截器（请求头）
        .addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                LogUtils.v("拦截器", message)
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY))
        .build()

    fun initRetrofit(): RetrofitManager {
        //处理过NULL判断的GSON
        mRetrofit = Retrofit.Builder()
            .baseUrl(ConstantUtils.BASE_URL)
            .client(mOkClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
        return this
    }

    fun initRetrofit(baseUrl: String): RetrofitManager {
        mRetrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(mOkClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
        return this
    }

    fun <T> getService(serviceClass: Class<T>): T {
        if (null != mRetrofit) {
            return mRetrofit!!.create(serviceClass)
        } else {
            throw UninitializedPropertyAccessException("Retrofit必须初始化")
        }
    }

}